package com.lzs.gateway.filter;



import com.alibaba.fastjson.JSON;


import com.lzs.gateway.entity.ActivierUser;
import com.lzs.gateway.entity.JwtUtils;
import com.lzs.gateway.entity.R;
import com.lzs.gateway.util.Sutil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
/**
 * @author 小刘先生
 * @date 2020/12/10 11:05
 */
//@Component
//@ConfigurationProperties(prefix = "anon")
//@Data
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private List<String> urls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.获取请求路径
        String path = request.getPath().toString();
//        int sindex = Sutil.findSindex(path, "/",4);
//        int count = Sutil.findStrCount(path, "/");
//        if (count>3){
//            path= path.substring(0,sindex);
//        }
//        System.out.println(path);
        //2.判断该路径是否为login
        if(path!=null && path.contains("/system/user/login")||path.contains("/json/map.json")){
            return chain.filter(exchange);//放行
        }
        //3.获取token
        String token = request.getHeaders().getFirst("token");
        //4.检验token 并解析
        if(!JwtUtils.checkToken(token)){
            return result(response,20002,"未登录");
        }

        //5. 判断当前请求路径是否是放行。
        if(urls.contains(path)){
            return chain.filter(exchange);
        }

        Long userId=JwtUtils.getMemberIdByJwtToken(token);
        //5.判断当前用户得权限。
        String s = redisTemplate.opsForValue().get("user::" + userId);
        ActivierUser activierUser=JSON.parseObject(s,ActivierUser.class);

        if(activierUser.getPermissions().contains(path)){
            return chain.filter(exchange);
        }else{
            return result(response,20003,"未授权");
        }
    }

    private Mono<Void> result(ServerHttpResponse response,Integer code,String msg){
        try {
            byte[] datas = JSON.toJSONString(R.error().code(code).message(msg)).getBytes("utf-8");
            DataBuffer buffer = response.bufferFactory().wrap(datas);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }catch (Exception e){
            throw new RuntimeException("");
        }
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
